
var Utils = {};


/**
 * 分页
 *
 * @param pageDomId				包含分页块的dom的ID
 * @param num_entries			数据总条数
 * @param pageselectCallback	点击页码回调函数
 * @param items_per_page		每页显示数据条数（默认10条）
 * @param num_edge_entries		边缘页数
 * @param um_display_entries	主体页数
 */
Utils.newPagination = function(pageDomId, num_entries, pageselectCallback, items_per_page,
						num_edge_entries, num_display_entries) {
	if($.trim(items_per_page) == "") {
		items_per_page = 10;
	}
	if($.trim(num_edge_entries) == "") {
		num_edge_entries = 2;
	}
	if($.trim(num_display_entries) == "") {
		num_display_entries = 6;
	}
	// 创建分页
	$("#"+pageDomId).pagination(num_entries, {
		num_edge_entries: num_edge_entries, //边缘页数
		num_display_entries: num_display_entries, //主体页数
		items_per_page: items_per_page, //每页显示数据条数
		prev_text: "上一页",
		next_text: "下一页",
		callback: pageselectCallback,
	});
};

/*
单图上传代码块

@param divId
@param imgHtml
@param imgCate
*/
Utils.upLoadImg = function(divId, imgHtml, imgCate) {
	if(document.all){	//IE浏览器
		imgHtml = "up-img-ie.html";
	}
	$("<div></div>").load(imgHtml, function(response, status, xhr) {
		response = response.replace(/up-img-form/g, "up-img-form"+"_"+divId);
		response = response.replace(/load-img/g, "load-img"+"_"+divId);
		response = response.replace(/preview-box/g, "preview-box"+"_"+divId);
		response = response.replace(/preview-img/g, "preview-img"+"_"+divId);
		response = response.replace(/sel-img-bt/g, "sel-img-bt"+"_"+divId);
		response = response.replace(/up-img-bts/g, "up-img-bts"+"_"+divId);
		response = response.replace(/upload-bt/g, "upload-bt"+"_"+divId);
		response = response.replace(/delete-bt/g, "delete-bt"+"_"+divId);
		response = response.replace(/loading-div/g, "loading-div"+"_"+divId);
		response = response.replace(/up-result-div/g, "up-result-div"+"_"+divId);
		response = response.replace(/up-img-result/g, "up-img-result"+"_"+divId);
		response = response.replace(/imgUrl/g, "imgUrl"+"_"+divId);
		response = response.replace(/imgCateNo/g, imgCate);
		$("#"+divId).html(response);
		
//		if(document.all){	//IE
//			$("#load-img"+"_"+divId).css("position", "absolute");
//			$("#load-img"+"_"+divId).css("clip", "rect(1px 1px 1px 1px)");
//			$("#load-img"+"_"+divId).css("display", "inline-block");
//		} else {	//非IE
//			$("#load-img"+"_"+divId).css("display", "none");
//		}
	});
};

/*
消息对话框
*/
Utils.msgDialog = function(msg) {
	var d = dialog({
			fixed: true,
			zIndex: 999999999,
    		title: '温馨提示',
  	  		content: msg,
			okValue: '确&nbsp;定',
    		ok: function () {}
	});
	d.width(350);
	d.showModal();
};

/*
确认对话框

@param content {String} 对话框内容
@param yesText {String} 确认按钮文字
@param noText {String} 取消按钮文字
@param succFunc {function} “确认”回调
@param failFunc {function} “取消”回调
*/
Utils.checkDialog = function(content, yesText, noText, succFunc, failFunc) {
	var d = dialog({
			fixed: true,
			zIndex: 999999999,
    		title: '温馨提示',
  	  		content: content,
			okValue: yesText,
    		ok: function () {
					succFunc();
				},
			button: [{
				value: noText,
            	callback: function () {
					failFunc();
            	},
            	autofocus: false
			}]
	});
	d.width(350);
	d.showModal();
};

/*
添加复制到剪切板功能

@param clickDom {js节点} 触发复制的元素
@param valDom {js节点}	复制内容的元素
*/
Utils.appendZclip = function(clickDom, valDom) {
	$(clickDom).zclip({
        path: 'js/zClip/ZeroClipboard.swf', //记得把ZeroClipboard.swf引入到项目中 
        copy: function() {
            return $(valDom).val();
        },
		beforeCopy: function() {
			//alert("开始复制了！");
		},
		afterCopy: function() {
			Utils.msgDialog('复制成功：&nbsp;&nbsp;按 <span style="color:#FF4100; font-weight:bold;">Ctrl+V</span> 粘贴');
		}
    });
};

/**
关闭当前页面
*/
Utils.closeCurrentPage = function() {
	//FF中需要修改配置window.close方法才能有作用，为了不需要用户去手动修改，所以用一个空白页面显示并且让后退按钮失效
	//Opera浏览器旧版本(小于等于12.16版本)内核是Presto，window.close方法有作用，但页面不是关闭只是跳转到空白页面，后退按钮有效，也需要特殊处理
	//var userAgent = navigator.userAgent;
//	if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Presto") != -1) {
//		window.location.replace("about:blank");
//	} else {
//		window.opener = null;
//		window.open("", "_self");
//		window.close();
//	}
	window.opener = null;
	window.open("", "_self");
	window.close();
};

/*
获取URL参数

@param name 参数名
*/
Utils.getUrlParam = function(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
		return decodeURI(r[2]);
	}
	return null;
};

/**
 * 将数值四舍五入(保留2位小数)后格式化成金额形式
 *
 * @param num 数值(Number或者String)
 * @return 金额格式的字符串,如'1,234,567.45'
 * @type String
 */
Utils.formatMoney = function(num) {
	if(num == null) {
		return null;
	}
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
		num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
//    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
//    	num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
//    }
    return (((sign)?'':'-') + num + '.' + cents);
};

/*
产生0-n的随机数
*/
Utils.getRandom = function(n) {
	return Math.floor(Math.random()*n+1)
};

/*
刷新用户信息
*/
Utils.refreshUserInfo = function() {
	AQ.callAQ("refreshUserInfo.do", null, function(result) {
		result[1].identityPic = DIC.IdentityPic[result[1].identityLevel];
		result[1].vipPic = DIC.VipPic[result[1].vip];
		$.cookie("userName", result[1].userName, {expires: 30});
		$.cookie("User", JSON.stringify(result[1]));
	}, function(err, code){
		console.log(err + "["+ code +"]");
	});
};

/* 获取当前日期 */
Utils.nowDate = function() {
	var date = new Date();
	var year = date.getFullYear()
	var month = date.getMonth() + 1
	var day = date.getDate();
//	var h = date.getHours(); 
//	var m = date.getMinutes(); 
//	var s = date.getSeconds();
	month = (""+month).length == 1 ? "0"+month : month;
	day = (""+day).length == 1 ? "0"+day : day;
	return year+"-"+month+"-"+day;
};

/* 
日期加减

@param dateA 日期：yyyy-MM-dd
@param addedDay 增加的（+/-）天数
*/
Utils.dateAdd = function(dateA, addedDay) {
	var date = new Date(dateA);
	date = date - addedDay * 24 * 60 * 60 * 1000 * -1;
	date = new Date(date);
	var year = date.getFullYear()
	var month = date.getMonth() + 1
	var day = date.getDate();
	month = (""+month).length == 1 ? "0"+month : month;
	day = (""+day).length == 1 ? "0"+day : day;
	return year+"-"+month+"-"+day;
};

/* 
字符串长度统计、区分中英文（汉字长度为2）
@param {String} 字符串
*/
Utils.countLength = function(str) {  
	var len = 0;
	var reg = /^[\u4E00-\u9FA5]{1}$/;
	for (var i=0; i<str.length; ++i) {
		var char = str.substr(i, 1);
		if(reg.test(char)) {
			len += 2;
		} else {
			len += 1;
		}
	}
	return len;  
};
